import pickle
import os
import torch



class GlobalVar:
    # 通过torch.hub(pytorch中专注于迁移学的工具)获得已经训练好的bert-base-chinese模型

    model = None
    # 获得对应的字符映射器, 它将把中文的每个字映射成一个数字
    tokenizer = None
    all_diseases = None
    @classmethod
    def variable_init(cls):
        GlobalVar.model = torch.hub.load('huggingface/pytorch-transformers', 'model', 'bert-base-chinese')
        GlobalVar.tokenizer = torch.hub.load('huggingface/pytorch-transformers', 'tokenizer', 'bert-base-chinese',
                                             TOKENIZERS_PARALLELISM=False)
        from att_query import get_all_dis_from_mysql
        GlobalVar.all_diseases = get_all_dis_from_mysql()

root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
session_path = root_path + '/conf/user_session.txt'


def get_usersession():
    f = open(session_path, 'rb')
    user_session = pickle.load(f)
    f.close()
    return user_session


def set_value(key, value):
    """ 定义一个全局变量 """
    user_session = get_usersession()
    user_session[key] = value
    f = open(session_path, 'wb')
    pickle.dump(user_session, f)
    f.close()


def get_value(key, defValue=[]):
    """ 获得一个全局变量,不存在则返回默认值 """
    user_session = get_usersession()

    try:
        return user_session[key]
    except KeyError:
        return defValue


def delete_key(key):
    user_session = get_usersession()
    del user_session[key]
    f = open(session_path, 'wb')
    pickle.dump(user_session, f)
    f.close()


def clear_user_session():
    dic = {}
    f = open(session_path, 'wb')
    pickle.dump(dic, f)
    f.close()


if __name__ == '__main__':
    from uuid import UUID

    clear_user_session()
    # set_value(1, 1)
    # sym = get_value('a7dc19c6-1e8f-11ec-8c87-1e00311eb05a')
    # for s in sym:
    #     print(s)
    #     for at in s.attributes:
    #         print(at)
    # print()
    # print(get_usersession())
    # delete_key(UUID('9e519bf2-1b55-11ec-afcf-1e00311eb05a'))
    pass
